from django import http
from django.core.cache import cache
from django.shortcuts import render
from django.views import View

from meiduo_mall.utils.response_code import RET
# Create your views here.
from .models import Area
from users.utils import MyLoginRequiredMiXinView


class AreaView(View):
    def get(self,request):
        # 前端逻辑：页面加载请求省份地址--> get_provinces()--> '/areas/'
        # 下拉框加载展示请求市区地址--> form_address.province_id--> '/areas/?area_id='
        area_id=request.GET.get("area_id")
        if not area_id: #请求省份地址
            # 返回data.province_list
            areas = Area.objects.filter(parent__isnull=True).all()
            # 获取缓存
            area_data_cache = cache.get("province_list")
            # print(area_data_cache)
            if area_data_cache:
                context = {
                    "code": RET.OK,
                    "errmsg": "OK",
                    "province_list":area_data_cache
                }
                return http.JsonResponse(context)
            # 数据转换
            province_list = []
            for area in areas:
                province = {
                    "id": area.id,
                    "name": area.name
                }
                province_list.append(province)

            # 拼接数据
            context = {
                "province_list": province_list,
                "code": RET.OK,
                "errmsg":"OK"
            }

            # 设置缓存数据
            cache.set('province_list',province_list,3600*24*2)
            # 返回数据
            return http.JsonResponse(context)


        else: #市区
            # <... :value="province.id" ...> 返回'data.sub_data.subs'
            # 获取区域
            area = Area.objects.get(id=area_id)

            # 获取缓存
            sub_data_cache = cache.get("sub_data_%s"%area_id)
            # print(sub_data_cache)
            if sub_data_cache:
                context = {
                    "code": RET.OK,
                    "errmsg": "OK",
                    "sub_data":sub_data_cache
                }
                return http.JsonResponse(context)
            # 获取子区域
            sub_data = area.subs.all()

            # 数据转换
            sub_list = []
            for sub in sub_data:
                sub_dict = {
                    "id":sub.id,
                    "name":sub.name
                }
                sub_list.append(sub_dict)

            # 数据拼接
            context = {
                "code":RET.OK,
                "errmsg": "OK",
                "sub_data":{
                    "subs":sub_list,
                    "id":area.id,
                    "name":area.name,
                }
            }

            # 设置缓存数据
            cache.set("sub_data_%s"%area_id,context["sub_data"],3600*24*2)

            # 返回数据
            return http.JsonResponse(context)
